<%--
  Created by IntelliJ IDEA.
  User: 86183
  Date: 2022/5/8
  Time: 14:50
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ page isELIgnored="false" %>
<html>
<head>
    <title>商家的页面</title>
    <link rel="shortcut icon" href="#"/>
    <style>
        body{
            color: white;
            background-color: black
        }
    </style>
</head>
<body>
<div>
    <button id="ordersButton">订单</button>
    <button id="sendTickets">发放抵用券</button>
    <button onclick="getMessage()">评价</button>
    <button onclick="getNotices()">通知</button>
    <button onclick="personalHomePage()">个人中心</button>
    <button id="shop">店铺信息</button>
    <button id="foods">菜单信息</button>
    <button onclick="complaint()">投诉</button>
    <button id="out">退出登录</button>
    <div id="controller">
    </div>
</div>
</body>
<script>
    let Tickets;
    let Orders;
    let Shop;
    let Foods;
    let shopId;
    let PageNow=1;
    let Page;
    document.getElementById("out").onclick= function (){
        document.cookie = "name=; expires=Thu, 01 Jan 1970 00:00:00 GMT";
        document.cookie = "id=; expires=Thu, 01 Jan 1970 00:00:00 GMT";
        document.cookie = "role=; expires=Thu, 01 Jan 1970 00:00:00 GMT";
        window.location ="index.jsp";
    }
    function complaint(){
        window.location="Complaint.jsp";
    }
    function thePage(objects){
        let page=objects.length/4;
        if(objects.length%4 == 0){return page;}
        return page+1;
    }
    function nextPage(){
        console.log(PageNow)
        console.log(Page)
        if(Page-(PageNow+1)>=0){addFood(++PageNow)}else{alert("这是最后一页了!")};
    }
    function beforePage(){
        if(PageNow>1){addFood(--PageNow)}else{alert("这是第一页了!")};
    }
    function getShopAndFood(){
        let shop={
            "ownerId":getCookie("id"),
            "mode":"getTheShopAndFoodByOwnerId"
        }
        let xhr=new XMLHttpRequest();
        xhr.open("post","http://localhost:80/intoShop",true);
        xhr.setRequestHeader('Content-Type','application/x-www-form-urlencoded')
        xhr.responseType='json';
        xhr.send("json="+JSON.stringify(shop));
        xhr.onreadystatechange=function(){
            if(xhr.status==200 && xhr.readyState==4){
                let data = xhr.response;
                console.log(data);
                if(data["code"]==404){
                    console.log(data.state);
                }else{
                    let json=JSON.parse(data.data);
                    Shop=json[0];
                    shopId=Shop["id"];
                    if(json.length==2){
                        Foods=json[1];
                        Page=thePage(Foods);
                    }
                    console.log(JSON.parse(data.data));
                    getTickets();
                }
            }
        }
    }
    getShopAndFood();
    function getCookie(name) {
        if (document.cookie.length > 0) {
            let start = document.cookie.indexOf(name + "=");
            if (start != -1) {
                start = start + name.length + 1;
                let end = document.cookie.indexOf(";", start);
                if (end == -1) end = document.cookie.length;
                return decodeURI(document.cookie.substring(start, end));
            }
        }
        return null;
    }
    function getTickets(){
        let shop={
            "shopId":Shop["id"],
            "mode":"hasTicket"
        }
        let xhr=new XMLHttpRequest();
        xhr.open("post","http://localhost:80/ticket",true);
        xhr.setRequestHeader('Content-Type','application/x-www-form-urlencoded')
        xhr.responseType='json';
        xhr.send("json="+JSON.stringify(shop));
        xhr.onreadystatechange=function(){
            if(xhr.status==200 && xhr.readyState==4){
                let data = xhr.response;
                console.log(data);
                if(data["code"]==404){
                    console.log(data.state);
                }else{
                    let json=JSON.parse(data.data);
                    console.log(json)
                    Tickets=json;
                }
            }
        }
    }
    document.getElementById("shop").onclick=function (){
        document.getElementById("controller").innerHTML=
            '<div>'+
            '<div style="display:inline-block;">' +
            '<img border="0" src=""  id="picture" alt="picture" width="200" height="200"></div>'+
            '<div style="display:inline-block;">'+
            Shop["name"]+'<h4>'+Shop["introduction"]+'</h4><h3>资产: '+Shop["money"]+' 元</h3><br>' +
            '<h5>地址: '+Shop["districtName"]+Shop["streetName"]+Shop["detailedAddress"]+'</h5></div>' +
            '<button style="margin-left: 10px" onclick="updateShop()">设置</button>';
        document.getElementById("picture").src="http://localhost/picture/upload/"+Shop["picture"];
    }
    function updateShop(){
        window.location="UpdateShop.jsp?name="+Shop["name"]+"&id="+Shop["id"]+"&introduction="+Shop["introduction"]+
            "&money="+Shop["money"]+"&districtName="+Shop["districtName"]+"&streetName="+Shop["streetName"]+
            "&detailedAddress="+Shop["detailedAddress"]+"&picture="+Shop["picture"];
    }
    document.getElementById("foods").onclick=function (){
        document.getElementById("controller").innerHTML='';
        addFood(1);
    }
    let params = new URLSearchParams(location.search);
    let state = params.get('state');
    if(state!=null){
        console.log(state);
        if(state=="SUCCESS"){
            alert("更新成功!!")
            window.location.href="Seller.jsp";
        }else{
            console.log("fail")
            alert(state)
            alert("操作失败,请稍后再试")
        }
    }
    function insertFood(){
        document.getElementById("controller").innerHTML+=
            `<form method="post" action="/FoodServlet" enctype="multipart/form-data">
            <!--label for="username">用户名：</label>-->
            <input type="hidden" name="action" value="insertNewFood">
            <input type="hidden" name="shopId" value="">
            名称：<input type="text" name="name" maxlength="10"><br>
            价格：<input type="number" name="price" max="99999" min="0" step="0.01"><br>
            <label for="pictureUrl">样式图片:</label>
            <input type="file" id="pictureUrl" name="pictureUrl"><br>
            <input type="submit"></form><button onclick="window.location.reload()">返回</button>`;
        document.getElementsByName('shopId')[0].value = shopId;
        console.log(shopId);
        console.log(document.getElementsByName('shopId')[0].value);
    }
    function insertOver(){
        let newFoodName=document.getElementById("newFoodName").value;
        let price=document.getElementById("price").value;
        console.log(newFoodName)
        console.log(price)
        if(price<0){alert("价格不能为负数!");return;}
        alert("stop");
        if(newFoodName!='' && price!='') {
            let newFood={
                "name":newFoodName,
                "price":price,
                "shopId":Shop["id"],
                "mode":"insertNewFood"
            }
            console.log("success");
            let xhr=new XMLHttpRequest();
            xhr.open("post","http://localhost:80/intoShop",true);
            xhr.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
            xhr.send("json="+JSON.stringify(newFood));
            xhr.responseType='json';
            xhr.onreadystatechange=function (){
                if(xhr.status==200 && xhr.readyState==4){
                    let data=xhr.response;
                    console.log(data);
                    console.log(data.data);
                    alert(data.state);
                    if(data.code==200){
                        window.location="Seller.jsp"
                    }
                }
            }
        }else{
            alert("菜式信息不完整!");
        }
    }
    function addFood(page){
        if(Foods==''){alert("您的菜单为空呢!");return;}
        let count=4;
        if(Page-page<1){
            count=Foods.length-(page-1)*4;
        }//C:\小A二轮\MeiTuan\web\picture\upload
        document.getElementById("controller").innerHTML='';
        for(let i=4*(page-1);i<count+4*(page-1);i++){
            document.getElementById("controller").innerHTML+=
                `<div>
                <div style="display:inline-block;margin-left: 10px" id="picture`+i+`"></div>
                <div style="display:inline-block;margin-left: 10px" id="`+i+`">名称:
                `+Foods[i]["name"]+`<br>价格:`+Foods[i]["price"]+` 元</div>
                <div style="display:inline-block;margin-left: 20px" id="update`+i+`">
                <button onclick="updateFood('`+i+`')">修改</button></div>
                </div><hr>`;
            let src="http://localhost/picture/upload/"+Foods[i]["picture"];
            document.getElementById("picture"+i).innerHTML=`<img border="0" src="`+src+`" alt="picture" width="160" height="100">`;
        }
        document.getElementById("controller").innerHTML+=
            '<button id="addFood" onclick="insertFood()">新增菜单</button><br><button '+
            'onclick="beforePage()">上一页</button>'+
            '<button '+
            'onclick="nextPage()">下一页</button>';
    }
    function updateFood(i){
        console.log(i);
        document.getElementById("update"+i).style.display="none";
        document.getElementById(i).innerHTML=
            `<form method="post" action="/FoodServlet" enctype="multipart/form-data">
        <input type="hidden" name="action" value="updateFood"/>
            <input type="hidden" name="foodId" value=""/>
            名称：<input type="text" name="name" maxlength="10" value="`+Foods[i]["name"]+`"/><br>
            价格：<input type="number" name="price" value="`+Foods[i]["price"]+`" max="99999" min="0" step="0.01"/><br>
            <label for="pictureUrl">样式图片:</label>
            <input type="file" id="pictureUrl" name="pictureUrl"/><br>
                <input type="submit"></form> <button onclick="window.location.reload()">返回</button>`;
        document.getElementsByName('foodId')[0].value = Foods[i]["id"];
    }
    function updateOver(i){
        let newName=document.getElementById("name"+i).value;
        let newPrice=document.getElementById("price"+i).value;
        if(newPrice<0){alert("价格不能为负数!");return;}
        console.log(newName);
        console.log(newPrice);
        let newFood={
            "name":newName,
            "foodId":Foods[i]["id"],
            "price":newPrice,
            "mode":"updateFood"
        }
        console.log("json="+JSON.stringify(newFood))
        let xhr=new XMLHttpRequest();
        xhr.open("post","http://localhost:80/intoShop",true);
        xhr.setRequestHeader('Content-Type','application/x-www-form-urlencoded')
        xhr.responseType='json';
        xhr.send("json="+JSON.stringify(newFood));
        xhr.onreadystatechange=function(){
            if(xhr.status==200 && xhr.readyState==4){
                let data = xhr.response;
                console.log(data);
                console.log(data.state);
                alert(data.state);
                if(data.code==200){
                    window.location="Seller.jsp";
                }
            }
        }

    }
    document.getElementById("sendTickets").onclick=function (){
        document.getElementById("controller").innerHTML=``;
        if(Tickets!=''){
            console.log(Tickets)
            console.log(Tickets.length);
            for(let i=0;i<Tickets.length;i++){
                document.getElementById("controller").innerHTML+=`
                抵用券折扣:`+Tickets[i]["discount"]+` 抵用券数量:`+Tickets[i]["number"]+`<br>`;
            }
        }
        document.getElementById("controller").innerHTML+=`<hr>请输入您要发放的抵用券折扣:
        <input type="number"  min="0" max="10" id="discount">
        <br>请输入您要发放的份数(请输入正整数):<input type="number" id="number"/><button onclick="sendTickets()">发放</button>`;
    }
    function sendTickets(){
        let discount=document.getElementById("discount").value;
        let number=document.getElementById("number").value;
        console.log(number)
        if(discount>0 && discount<10) {
            let ticket;
            ticket = {
                "shopId": Shop["id"],
                "discount": discount,
                "mode": "insertTicket",
                "number": number
            }
            console.log(number)
            if(number==''){
                alert("number could not be empty!");
                return;
            }
            if(number<0){
                alert("number could not be a negative")
                return;
            }
            if(number-parseInt(number)>0){alert("份数必须为正整数!");return;}
            if (Tickets != '') {
                for (let i = 0; i < Tickets.length; i++) {
                    if (discount == Tickets[i]["discount"]) {
                        console.log(Tickets[i]["discount"])
                        console.log(discount)
                        number += Tickets[i]["number"];
                        console.log(number)
                        ticket = {
                            "shopId": Shop["id"],
                            "discount": discount,
                            "mode": "updateTicket",
                            "number": number
                        }
                    }
                }
            }
            sendTicketFinal(ticket);
        }else {
            alert("折扣必须在1-10折以内!");
        }
    }
    function sendTicketFinal(json){
        console.log("json:"+JSON.stringify(json))
        let xhr=new XMLHttpRequest();
        xhr.open("post","http://localhost:80/intoShop",true);
        xhr.setRequestHeader('Content-Type','application/x-www-form-urlencoded')
        xhr.responseType='json';
        xhr.send("json="+JSON.stringify(json));
        xhr.onreadystatechange=function(){
            if(xhr.status==200 && xhr.readyState==4){
                let data = xhr.response;
                console.log(data);
                if(data["code"]==404){
                    console.log(data.state);
                    alert(data.state);
                }else{
                    console.log(JSON.parse(data.data));
                    alert(data.state);
                    window.location="Seller.jsp";
                }
            }
        }
    }
    document.getElementById("ordersButton").onclick=function (){
        document.getElementById("controller").innerHTML=
            '<button id="all" onclick="senOrders(getAllOrders())">所有订单</button>' +
            '<button id="over" onclick="senOrders(getOverOrders())">已完成订单</button>' +
            '<button id="ing"  onclick="senOrders(getIngOrders())">进行中订单</button>';

    }
    function getAllOrders(){
        let json={
            "id":Shop["id"],
            "mode":"orders",
            "state":null,
        }
        return json;
    }
    function getOverOrders(){
        let json={
            "id":Shop["id"],
            "mode": "orders",
            "state": "已完成"
        }
        return json;
    }
    function getIngOrders(){
        let json={
            "id":Shop["id"],
            "mode": "orders",
            "state": "未接单"
        }
        return json;
    }
    function senOrders(json){
        console.log("json:"+JSON.stringify(json))
        let xhr=new XMLHttpRequest();
        xhr.open("post","http://localhost:80/intoShop",true);
        xhr.setRequestHeader('Content-Type','application/x-www-form-urlencoded')
        xhr.responseType='json';
        xhr.send("json="+JSON.stringify(json));
        xhr.onreadystatechange=function(){
            if(xhr.status==200 && xhr.readyState==4){
                let data = xhr.response;
                console.log(data);
                if(data["code"]==404){
                    console.log(data.state);
                    alert(data.state);
                }else{
                    console.log(JSON.parse(data.data));
                    Orders=JSON.parse(data.data);
                    document.getElementById("controller").innerHTML='';
                    for(let i=Orders.length-1;i>=0;i--){
                        document.getElementById("controller").innerHTML+=
                            '内容:  '+Orders[i]['content']+'<br>'+
                            '买家:  '+Orders[i]['ownerName']+'<br>'+
                            '价格:  '+Orders[i]['cost']+'  元<br>'+
                            '状态:  '+Orders[i]['state'];
                        if(Orders[i]['state']=='未接单'){
                            document.getElementById("controller").innerHTML+=
                                `<button id="`+i+`" style="margin-left: 5px"` +
                                ` onclick="updateOrders(`+i+`,'已拒绝')">拒单</button>`+
                                `<button id="`+i+`" style="margin-left: 5px"` +
                                ` onclick="updateOrders(`+i+`,'已完成')">接单</button>`;
                        }
                        document.getElementById("controller").innerHTML+=
                            '<br>点餐时间:'+Orders[i]['orderTime']+'<br>'+
                            '完成时间:'+Orders[i]['updateTime']+'<br>'+'<hr>';
                    }
                }
            }
        }
    }
    function updateOrders(i,state){
        let orders={
            "id":Shop["id"],
            "ordersId":Orders[i]["id"],
            "state":state,
            "cost":Orders[i]["cost"],
            "buyerId":Orders[i]["buyerId"],
            "mode":"updateOrders"
        }
        console.log("json="+JSON.stringify(orders))
        let xhr=new XMLHttpRequest();
        xhr.open("post","http://localhost:80/intoShop",true);
        xhr.setRequestHeader('Content-Type','application/x-www-form-urlencoded')
        xhr.responseType='json';
        xhr.send("json="+JSON.stringify(orders));
        xhr.onreadystatechange=function(){
            if(xhr.status==200 && xhr.readyState==4){
                let data = xhr.response;
                console.log(data);
                console.log(data.state);
                alert(data.state);
                window.location="Seller.jsp";
            }
        }

    }
    function getMessage(){
        window.location="Message.jsp?shopId="+Shop["id"];
    }
    function personalHomePage(){
        window.location="Something.jsp";
    }
    function getNotices(){
        let xhr=new XMLHttpRequest();
        xhr.open("post","http://localhost:80/notice",true);
        xhr.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
        console.log(getCookie("role"))
        let role={
            "role":getCookie("role"),
            "id":getCookie("id"),
            "mode":"getNotice"
        }
        xhr.send("json="+JSON.stringify(role));
        console.log("before:role="+JSON.stringify(role));
        xhr.onreadystatechange=function (){
            if(xhr.status==200 && xhr.readyState==4){
                let data=xhr.response;
                console.log(data)
                let json=JSON.parse(data)
                console.log(json)
                console.log(json.code)
                if(json.code==200 && json.state=='SUCCESS'){
                    let notice=JSON.parse(json.data);
                    console.log(notice);//ok
                    document.getElementById("controller").innerHTML='';
                    for(let i=0;i<notice.length;i++){
                        document.getElementById("controller").innerHTML+=
                            '消息:<text>'+notice[i]['content']+'</text><br>'+
                            '时间:<text>'+notice[i]['updateTime']+'</text><br>'+'<hr>';
                    }

                }else if(json.code==404){
                    console.log(json.state)
                    alert(json.state);
                }
            }
        }
    }
</script>
</html>
